package com.lemurian.bankdata.action.business;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.lemurian.bankdata.dto.DelegasiKurirDTO;
import com.lemurian.bankdata.dto.LogHelper;
import com.lemurian.bankdata.lite.authentication.BankDataPrincipal;
import com.lemurian.bankdata.lite.enums.UserActivityType;
import com.lemurian.bankdata.lite.enums.UserType;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.struts.Pager;
import com.lemurian.bankdata.lite.struts.PartialList;
import com.lemurian.bankdata.lite.utils.GeneralConstant;
import com.lemurian.bankdata.services.ActivityLogService;
import com.lemurian.bankdata.services.CourierService;
import com.lemurian.bankdata.services.ManagementService;
import com.lemurian.bankdata.utils.BaseAction;
import com.lemurian.entity.Courier;
import com.lemurian.entity.Management;
import com.lemurian.entity.User;
import com.opensymphony.xwork2.Preparable;

public class DelegasiKurirAction extends BaseAction implements Preparable {

	private static final long serialVersionUID = 1L;

	private BankDataLogger log = BankDataLogger.getLogger(DelegasiPengetikanAction.class.getSimpleName());
	
	private List<Management> managements = new ArrayList<Management>();
	
	private List<Courier> listKurir;
	private List<DelegasiKurirDTO> listId;
	
	private String nama = "";
	
	private User user;
	private BankDataPrincipal principal;
	
	@Autowired
	private ManagementService managementService;
	@Autowired
	private CourierService courierService;
	
	@Autowired 
	private ActivityLogService userActivityLogService;
	private LogHelper userActivityLog;
	
	@Override
	public void prepare() throws Exception {
		log.info(": : : : : ON DELEGASI KURIR ");
		
		principal = (BankDataPrincipal) getSession().get(GeneralConstant.USER_PRINCIPAL);
		user = principal.getUser();
	}
	
	@Override
	public String list() {
		setPreviousPage(GeneralConstant.LIST);
		
		try {
			listKurir = courierService.findAll();
			
			/* LIST CERTIFICATE */
			Criterion criterion = null;
			
			log.info(": : : : : USER TYPE ID "+user.getUserType().getId());
			if(user.getUserType().getId() == UserType.ADMINISTRATOR.id()) {
				criterion = Restrictions.ne("id", new Integer(-1));
			} else {
				criterion = Restrictions.eq("department.id", user.getDepartment().getId());
			}
			
			PartialList<Management> partialList = managementService.delegasiKurirList(getStart(), getCount(), getAscDesc().equalsIgnoreCase("desc") ? Order.desc(getOrderBy().length() > 0 ? getOrderBy() : "id") : Order.asc(getOrderBy().length() > 0 ? getOrderBy() : "id"),
					nama.length() > 0 ? Restrictions.ilike("debitur.name", nama, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					criterion);
			
			managements = partialList.getList();
			
			setPager(Pager.generatePager(getStart(), getCount(), partialList.getTotal()));
            setPagerItem(Pager.generatePagerItem(getStart(), getCount(), partialList.getTotal()));

            partialList = null;
			
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		setMappedRequest(GeneralConstant.LIST);
        return SUCCESS;
	}
	
	@Override
	public String save() {
		
		Management management = null;
		Courier courier = null;
		
		if(listId != null && listId.size() > 0) {
			for(DelegasiKurirDTO dp : listId) {
				
				if(dp.getManagementId() > 0 && dp.getCourierId() > 0) {
					
					log.sInfo(": : : : CLIENT  ID [%s]", dp.getManagementId());
					
					management = managementService.load(dp.getManagementId());
					
					log.sInfo(": : : : COURIER ID [%s]", dp.getCourierId());
					
					courier = courierService.load(dp.getCourierId());
					
					if(management != null && courier != null) {
							
						userActivityLog = new LogHelper(user, UserActivityType.DELEGATE_COURIER);
						
			            try {
			            	management.setCourier(courier);
							managementService.save(management);
			            	
			                log.sInfo(" :: User [%s:%s] is successfully delegate management [%s] to courier [%s]", user.getId(), user.getName(), management.getProcess(), courier.getName());

			                //check if activity is success
			                userActivityLog.setStatus(LogHelper.SUCCESS_ACTIVITY);
			            } catch (Exception e) {
			                log.sInfo(" :: Error was raised when User [%s:%s] delegate management [%s] to courier [%s]", user.getId(), user.getName(), management.getProcess(), courier.getName());
			                
			                //set activity log status into failed
			                userActivityLog.setStatus(LogHelper.FAILED_ACTIVITY);
			                userActivityLog.setErrorMsg(e.getMessage());
			            }
			            //save activity log
			            userActivityLog.setSessionId(ServletActionContext.getRequest().getSession().getId());
			            userActivityLog.getAdditionalParams().add(management.getProcess());
			            userActivityLog.getAdditionalParams().add(courier.getName());
			            userActivityLogService.saveUserActivity(userActivityLog);
					} else {
						continue;
					}
					
				}
				
			}
			
			addCustomActionMessage("Successfully delegate courier");
		} else {
			addCustomActionError("Failed delegate courier");
		}
		
		setMappedRequestFullPath("/DelegasiKurirAction_list.do");
		return GeneralConstant.REDIRECT;
	}
	
	@Override
	public String add() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String delete() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String detail() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String edit() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String update() {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Courier> getListKurir() {
		return listKurir;
	}

	public void setListKurir(List<Courier> listKurir) {
		this.listKurir = listKurir;
	}

	public List<DelegasiKurirDTO> getListId() {
		return listId;
	}

	public void setListId(List<DelegasiKurirDTO> listId) {
		this.listId = listId;
	}

	public String getNama() {
		return nama;
	}

	public void setNama(String nama) {
		this.nama = nama;
	}
	
}